package com.yxhl.zoume.core.specialcar.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.yxhl.zoume.R;
import com.yxhl.zoume.UIConstants;
import com.yxhl.zoume.common.ui.activity.base.BaseActivityWithToolBar;
import com.yxhl.zoume.core.specialcar.fragment.SpecialCarScheduleMapFragment;
import com.yxhl.zoume.core.specialcar.model.CancelSpecialCarOrderEvent;
import com.yxhl.zoume.core.specialcar.model.DialTelephoneEvent;
import com.yxhl.zoume.core.specialcar.model.OperationForToolbar;
import com.yxhl.zoume.core.specialcar.presenter.CancelSpecialCarPresenter;
import com.yxhl.zoume.core.specialcar.view.SpecialCarScheduleView;
import com.yxhl.zoume.core.tripsmgmt.ui.event.CancelTripOrderEvent;
import com.yxhl.zoume.data.rxbus.RxBus;
import com.yxhl.zoume.di.component.car.DaggerSpecialCarComponent;
import com.yxhl.zoume.di.component.car.SpecialCarComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.di.module.car.SpecialCarModule;
import com.yxhl.zoume.utils.DeviceUtils;
import com.yxhl.zoume.utils.DiskCacheUtils;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.PromptUtils;
import com.yxhl.zoume.utils.permission.PermissionHelper;

import javax.inject.Inject;

import butterknife.BindView;
import rx.functions.Action1;

/**
 * 包车出行
 */
public class SpecialCarScheduleActivity extends BaseActivityWithToolBar implements SpecialCarScheduleView {

    private static final String TAG = "SpecialCarScheduleAct";

    @BindView(R.id.frame_special_car_service_body)
    FrameLayout mServiceBodyFrame;
    @Inject
    CancelSpecialCarPresenter mCancelSpecialCarPresenter;
    //arguments
    private String mOrderId;
    private SpecialCarScheduleMapFragment mCurrentFragment;

    public static Intent getCallingIntent(Activity activity, String specialCarOrderId) {
        Intent launch = new Intent(activity, SpecialCarScheduleActivity.class);
        launch.putExtra(UIConstants.Car.INTENT_KEY_SPECIAL_ORDER_SERVICE_ORDER_ID, specialCarOrderId);
        return launch;
    }

    /**
     * 推送专用
     *
     * @param context
     * @param specialCarOrderId
     * @return
     */
    public static Intent getPushIntent(Context context, String specialCarOrderId) {
        Intent launch = new Intent(context, SpecialCarScheduleActivity.class);
        launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        launch.putExtra(UIConstants.Car.INTENT_KEY_SPECIAL_ORDER_SERVICE_ORDER_ID, specialCarOrderId);
        return launch;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleIntent();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntent();
    }

    private void handleIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            mOrderId = intent.getStringExtra(UIConstants.Car.INTENT_KEY_SPECIAL_ORDER_SERVICE_ORDER_ID);
            LOG.e(TAG, "SpecialCarScheduleAct mOrderId=" + mOrderId);
            DiskCacheUtils.getInstance(this).saveSpecialCarOrderId(mOrderId);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mCancelSpecialCarPresenter.attachView(this);
        onRxBusEvent();
        initializeShow(mOrderId);
    }

    private void initializeShow(String orderId) {
        mCurrentFragment = SpecialCarScheduleMapFragment.newInstance(orderId);
        addFragment(R.id.frame_special_car_service_body, mCurrentFragment);
    }


    @Override
    public void renderDataOnSuccess() {
        PromptUtils.showShort(this, getString(R.string.cancel_order_success));
        this.finish();
    }

    @Override
    public void renderDataOnFailure(String errorMessage) {
        PromptUtils.showShort(this, errorMessage);
    }


    public void onRxBusEvent() {
        Action1<CancelSpecialCarOrderEvent> cancelSpecialCarOrderEventAction =
                new Action1<CancelSpecialCarOrderEvent>() {
                    @Override
                    public void call(CancelSpecialCarOrderEvent cancelSpecialCarOrderEvent) {
                        if (TextUtils.isEmpty(mOrderId)) {
                            mOrderId = DiskCacheUtils.getInstance(SpecialCarScheduleActivity.this).getSpecialCarOrderId();
                        }
                        LOG.e(TAG, "onRxBusEvent specialOrderId=" + mOrderId);
//                mCancelSpecialCarPresenter.cancelSpecialCarOrder(mOrderId);
                        getAppComponent().navigator().navigateToSpecialCarOrderCancel(SpecialCarScheduleActivity.this, mOrderId);
//                        finish();
                    }
                };
        getCompositeSubscription().add(RxBus.getInstance().toSubscription(
                CancelSpecialCarOrderEvent.class, cancelSpecialCarOrderEventAction
        ));

        getCompositeSubscription().add(toSubscription(CancelTripOrderEvent.class, new Action1<CancelTripOrderEvent>() {
            @Override
            public void call(CancelTripOrderEvent event) {
                finish();
            }
        }));
    }


    @Override
    public void onBackPressed() {
        if (mCurrentFragment != null) {
            PopupWindow phonePopupWindow = mCurrentFragment.getPhonePopupWindow();
            if (phonePopupWindow != null) {
                if (phonePopupWindow.isShowing()) {
                    phonePopupWindow.dismiss();
                } else {
                    super.onBackPressed();
                    overridePendingTransition(R.anim.right_enter, R.anim.noanimation);
                }
            } else {
                super.onBackPressed();
                overridePendingTransition(R.anim.right_enter, R.anim.noanimation);
            }
        } else {
            super.onBackPressed();
            overridePendingTransition(R.anim.right_enter, R.anim.noanimation);
        }

    }


    @Override
    protected void onHeaderLeftClick(View view) {
        onBackPressed();
    }

    @Override
    protected void onHeaderRightClick(View view) {
        if (view instanceof TextView) {
            TextView rightTv = (TextView) view;
            String operationStr = rightTv.getText().toString().trim();
            switch (operationStr) {
                case OperationForToolbar.CANCEL_TRIP:
                    RxBus.getInstance().send(new CancelSpecialCarOrderEvent());

                    break;
                case OperationForToolbar.CUSTOMER_SERVICE:
                    if (PermissionHelper.checkPhonePermission(this)) {
                        DeviceUtils.dialTelPhone(this, getString(R.string.service_mobile));
                    } else {
                        PermissionHelper.takeCallPhonePermission(this, PermissionHelper.REQUEST_CODE_CALL_CUSTOMER_SERVICE);
                    }
                    break;
            }
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_special_car_schedule;
    }

    @Override
    protected void initializeInjector() {
        SpecialCarComponent specialCarComponent = DaggerSpecialCarComponent.builder()
                .appComponent(getAppComponent())
                .activityModule(new ActivityModule(this))
                .specialCarModule(new SpecialCarModule())
                .build();
        specialCarComponent.inject(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            //打电话给司机
            case PermissionHelper.REQUEST_CODE_CALL_SPECIAL_CAR_DRIVER:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    RxBus.getInstance().send(new DialTelephoneEvent(DialTelephoneEvent.FROM_SCHEDULE_DRIVER_MOBILE));
                } else {
                    PromptUtils.showShort(this, getString(R.string.special_car_schedule_deny_hint));
                }
                break;
            //打电话给客服
            case PermissionHelper.REQUEST_CODE_CALL_CUSTOMER_SERVICE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    DeviceUtils.dialTelPhone(this, getString(R.string.service_mobile));
                } else {
                    PromptUtils.showShort(this, getString(R.string.special_car_schedule_deny_hint));
                }
                break;
        }
    }


}
